



# -*- coding: utf-8 -*-
import logging
from datetime import datetime
from typing import List, Dict

from openpyxl import Workbook
from openpyxl.formatting.rule import FormulaRule
from openpyxl.styles import Alignment
from openpyxl.styles import PatternFill, Font

# 配置日志
logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)


class ExportHandler:

    # 预定义颜色格式
    FORMATS = {
        '无法抓取': FormulaRule(formula=['$F1="无法抓取"'],
                                fill=PatternFill(start_color='FFFFC7CE', end_color='FFFFC7CE')),
        '已删除': FormulaRule(formula=['$F1="已删除"'],
                              fill=PatternFill(start_color='FFFFFF99', end_color='FFFFFF99')),
        '失效': FormulaRule(formula=['$F1="失效"'],
                            fill=PatternFill(start_color='FFD9D9D9', end_color='FFD9D9D9'))
    }
    RED_FILL = PatternFill(start_color='FFFFC7CE', end_color='FFFFC7CE', fill_type='solid')
    HEADER_FONT = Font(bold=True, color='FFFFFF')
    HEADER_FILL = PatternFill(start_color='4F81BD', fill_type='solid')
    # 列宽配置
    COLUMN_WIDTH = {
        'A': 60,  # 链接
        'B': 15,  # 平台
        'C': 12,  # 点赞
        'D': 12,  # 评论
        'E': 12,  # 转发
        'F': 15  # 状态
    }

    @classmethod
    def export_to_excel(cls, data, save_path):
        """增强版Excel导出方法"""
        try:
            if not data:
                raise ValueError("导出数据不能为空")

            wb = Workbook()
            ws = wb.active
            ws.title = "抓取数据"

            # 写入表头
            headers = ['链接', '平台', '点赞', '评论', '转发', '状态']
            ws.append(headers)

            # 设置表头样式
            for col in range(1, 7):
                cell = ws.cell(row=1, column=col)
                cell.font = cls.HEADER_FONT
                cell.fill = cls.HEADER_FILL
                cell.alignment = Alignment(horizontal='center')

            # 写入数据并标记颜色
            failed_count = 0
            for row_idx, item in enumerate(data, start=2):
                ws.append([
                    item.get('url', ''),
                    item.get('platform', '未知'),
                    cls._safe_number(item.get('likes', 0)),
                    cls._safe_number(item.get('comments', 0)),
                    cls._safe_number(item.get('shares', 0)),
                    item.get('status', '未知')
                ])

                # 标记无法抓取的行
                if item.get('status') == '无法抓取':
                    failed_count += 1
                    for col in range(1, 7):
                        ws.cell(row=row_idx, column=col).fill = cls.RED_FILL

            # 自动调整列宽
            for col in ws.columns:
                max_length = 0
                column = col[0].column_letter
                for cell in col:
                    try:
                        if len(str(cell.value)) > max_length:
                            max_length = len(str(cell.value))
                    except:
                        pass
                adjusted_width = (max_length + 2) * 1.2
                ws.column_dimensions[column].width = adjusted_width

            # 添加日志工作表
            log_ws = wb.create_sheet("抓取日志")
            log_data = [
                ["导出时间", datetime.now().strftime('%Y-%m-%d %H:%M:%S')],
                ["总记录数", len(data)],
                ["成功记录", sum(1 for d in data if d.get('status') == '正常')],
                ["新增点赞", sum(d.get('likes', 0) for d in data)],
                ["失败记录", failed_count],
                ["失败链接", sum(1 for d in data if d['status'] == '无法抓取')],
                ["抓取时间", datetime.now().strftime('%Y-%m-%d %H:%M:%S')],
                ["备注", "生成于多平台数据采集系统"]
            ]
            for row in log_data:
                log_ws.append(row)

            # 保存文件
            wb.save(save_path)
            return True
        except Exception as e:
            logger.error(f"导出失败: {str(e)}", exc_info=True)
            return False

    @staticmethod
    def _safe_number(value):
        """安全转换数字格式"""
        try:
            return int(value)
        except (ValueError, TypeError):
            return 0




# 示例用法
if __name__ == '__main__':
    test_data = [
        {'url': 'http://example.com', 'platform': '微博',
         'likes': 1000, 'comments': 200, 'shares': 300, 'status': '正常'},
        {'url': 'http://invalid.com', 'platform': '未知',
         'likes': 0, 'comments': 0, 'shares': 0, 'status': '无法抓取'}
    ]

    path = ExportHandler.export_to_excel(test_data, "测试项目.xlsx")
    if path:
        print(f"导出成功，文件路径: {path}")



